<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		useRoute
	} from 'vue-router'
	import Poster from '@/components/poster.vue'
	import {
		baseUrl,
		appid,
		h5TitleRight
	} from "@/config/index.js"
	import {
		getInfo2Api,
		addRecommendApi
	} from "@/assets/api/other/invite.js"
	import {
		getInfoApi
	} from "@/assets/api/other/login.js"
	import {
		memorialHallApi,
		relationApi
	} from "@/assets/api/other/memorialHall.js"
	import {
		getRelationListApi
	} from "@/assets/api/other/space.js"
	import {
		redirectToToHome,
		navigateToLogin
	} from '@/assets/scripts/navigate'
	import post from '@/assets/pic/recommend/post.png'

	const familyPopup = ref()
	const relationPicker = ref()
	const posterImage = ref('')
	const userId = ref('')
	const meMemorialId = ref('')
	const dataSource = ref({})
	const title = ref('邀请您加入纪念馆')
	const tip = ref('亲朋好友等您加入，现邀请您与我们共同缅怀逝者')
	const qrcode = ref('')
	const pageParams = ref('')
	const userInfo = ref({})
	const userInfo2 = ref({})
	const relation = ref('')
	const familyList = ref([])

	const relationColumnData = [
		['儿子', '女儿', '孙子', '孙女', '外孙', '外孙女', '外甥', '外甥女', '侄子侄女', '儿媳', '女婿', '孙媳妇', '孙女婿', '外孙媳妇', '外孙女婿', '外甥媳妇',
			'外甥女婿', '侄媳妇', '侄女婿', '外孙/外孙女', '孙子/孙女', '儿子/女儿', '侄子/侄女', '外甥外甥女', '侄儿', '子侄辈', '后裔'
		],
		['丈夫', '妻子', '姐姐', '妹妹', '哥哥', '弟弟', '表哥', '表姐', '堂哥', '堂姐', '堂弟', '堂妹', '表弟', '表妹', '表嫂', '表姐夫', '姐夫',
			'嫂子',
			'弟媳', '弟妹', '哥姐', '妹夫'
		],
		['父亲', '母亲', '伯伯', '伯母', '叔叔', '婶婶', '姑姑', '姑父', '姨妈', '姨夫', '舅舅', '舅妈', '双亲', '父母', '公婆', '岳父母'],
		['挚友', '亲友', '朋友', '战友', '老师', '同学', '学生', '领导', '同事', '邻居', '远亲'],
		['祖父', '祖母', '外祖父', '外祖母', '祖父母', '外祖父母'],
		['粉丝', '故人', '男朋友', '女朋友', '其他'],
	]

	const relationColumns = ref([
		[
			'儿孙辈', '同辈', '父辈', '亲朋好友', '祖辈', '其他'
		],
		[]
	])

	const familyBtn_handleConfirm = async () => {
		if (!relation.value) {
			uni.showToast({
				title: '请选择关系',
				icon: 'none'
			})
			return
		}

		const res = await relationApi({
			isPass: '否',
			isAdmin: '否',
			meMemorialId: meMemorialId.value,
			relation: relation.value,
		})

		if (res.code === 200) {
			uni.showToast({
				title: '成功',
				icon: 'success',
				complete: () => {
					familyPopup.value.close()
					relation.value = ''
					redirectToToHome()
				}
			})
		}
	}

	const handleSelectRelation = () => {
		relationPicker.value.setColumnValues(1, relationColumnData[0])
		relationPicker.value.open()
	}

	const relation_handleChange = (e) => {
		if (e.columnIndex === 0) {
			relationPicker.value.setColumnValues(1, relationColumnData[e.index])
		}
	}

	const relation_handleConfirm = (e) => {
		relation.value = e.value[1]
		relationPicker.value.close()
	}

	const handleAgree = async () => {
		if (familyList.value.some(o => o.userId == userInfo.value.userId)) {
			uni.showToast({
				title: '已成为亲友，无需重复',
				icon: 'error'
			})
			return
		}
		familyPopup.value.open()
	}

	// 海报生成成功回调
	const onPosterSuccess = (imageUrl) => {
		posterImage.value = imageUrl
	}

	// 海报生成失败回调
	const onPosterError = (error) => {
		console.error('海报生成失败:', error)
		uni.showToast({
			title: '海报生成失败',
			icon: 'error'
		})
	}

	// 初始化二维码链接
	const qrcode_init = () => {
		qrcode.value = baseUrl + `/pages/others/login?pageParams=` +
			`/pages/others/invite/result?userId=${userInfo2.value.userId}&meMemorialId=${meMemorialId.value}`
	}

	onMounted(() => {
		route_init()
		data_init()
		pageParams_init()
		userInfo_init()
		userInfo2_init()
		familyList_init()
	})

	const route_init = async () => {
		const route = useRoute()
		if (route.query.userId && route.query.userId !== 'undefined') {
			userId.value = route.query.userId
		}
		if (route.query.meMemorialId && route.query.meMemorialId !== 'undefined') {
			meMemorialId.value = route.query.meMemorialId
		}
	}

	const data_init = async () => {
		const res = await memorialHallApi(meMemorialId.value)
		if (res.code === 200) {
			dataSource.value = res.data
			if (dataSource.value.mmType == 'mm_type_two') {
				tip.value = `加入${dataSource.value.mmName1} & ${dataSource.value.mmName2}的纪念馆，与我缅怀逝者、祭奠逝者`
			} else {
				tip.value = `加入${dataSource.value.mmName1}的纪念馆，与我缅怀逝者、祭奠逝者`
			}
		}
	}

	const pageParams_init = () => {
		pageParams.value = '/pages/others/invite/result?userId=' + userId.value + '&meMemorialId=' + meMemorialId.value
	}

	const userInfo_init = async () => {
		const res = await getInfoApi()
		if (res.code === 200) {
			userInfo.value = res.user
			uni.setStorageSync('user', res.user)
		} else {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'error',
				complete: () => {
					navigateToLogin(pageParams.value)
				}
			})
		}
	}

	const userInfo2_init = async () => {
		if (!userId.value) {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'error',
				complete: () => {
					navigateToLogin(pageParams.value)
				}
			})
			return
		}

		const res = await getInfo2Api(userId.value)
		if (res.code === 200) {
			userInfo2.value = res.user
			qrcode_init()
		} else {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'error',
				complete: () => {
					navigateToLogin(pageParams.value)
				}
			})
		}
	}

	const familyList_init = async () => {
		const res = await getRelationListApi(meMemorialId.value)
		if (res.code === 200) {
			familyList.value = res.rows
		}
	}
</script>

<template>
	<view>
		<uv-picker ref="relationPicker" :columns="relationColumns" style="z-index: 13000;"
			@change="relation_handleChange" @confirm="relation_handleConfirm"></uv-picker>

		<uv-popup ref="familyPopup" mode="center" round='10' closeable>
			<view class="family-popup">
				<view class="font-fs20 font-wb d-flex d-flex-jcc color-333">
					欢迎你加入亲友团
				</view>
				<view class="px-big mt-big">
					<uv-input placeholder="如儿子,女儿" disabled border="none" v-model="relation"
						@click="handleSelectRelation" :customStyle="{height:'46px', padding:'0 15px'}">
						<template v-slot:prefix>
							<uv-text text="您是逝者的:" margin="0 3px 0 0" type="tips"></uv-text>
						</template>
					</uv-input>
				</view>
				<view class="px-big mt-big">
					<view class="px-big">
						<uv-button type="success" text="确定" shape='circle' @click="familyBtn_handleConfirm"></uv-button>
					</view>
				</view>
			</view>
		</uv-popup>

		<uv-navbar :fixed="false" bgColor="#ff5000" :titleStyle="{color:'#fff'}" leftIcon="home-fill"
			leftIconColor="#fff" @leftClick="redirectToToHome" :title="h5TitleRight">
		</uv-navbar>

		<!-- 海报组件 -->
		<Poster v-if="qrcode" :avatar="userInfo2.avatar" :nickName="userInfo2.nickName || ''" :title="title"
			:postImage="post" :tip="tip" :qrcodeUrl="qrcode" :width="750" :ratio="0.5" @ok="onPosterSuccess"
			@error="onPosterError" />

		<view class="p-big box">
			<uv-button @click="handleAgree" text="接受邀请-加入亲友团" shape="circle"
				color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))">
			</uv-button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.family-popup {
		width: 300px;
		padding: 40px 0;

		.color-333 {
			color: #333333;
		}
	}

	.box {
		background-color: #ff971b;
	}

	.image {
		display: block;
		width: 100%;
	}

	.image-fill-x {
		width: 100%;
	}

	.px-big {
		padding-left: 20px;
		padding-right: 20px;
	}

	.mt-big {
		margin-top: 20px;
	}

	.p-big {
		padding: 20px;
	}
</style>